import com.fasterxml.jackson.databind.ObjectMapper;
import sun.applet.resources.MsgAppletViewer_es;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 保存和获取接口
 */
class Message {
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    // 保存
    //private ArrayList<Message> messages = new ArrayList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理提交消息请求
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //messages.add(message);
        save(message);
        // 通过 ContentType 来告知页面，返回的数据是 json 类型的
        // 有了这样的声明，此时 jquery ajax 就会自动把body的字符串转成 js 对象
        // 如果没有，jquery ajax 就只是当成字符串来处理
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write("{ \"ok\" : true }");
    }

    // 获取
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取消息队列，把消息队列中的内容全部返回给客户端
        // 使用 ObjectMapper 把 Java 对象转成 JSON 格式字符串
        resp.setContentType("application/json; charset=utf8");
        String jsonString = objectMapper.writeValueAsString(load());
        System.out.println("jsonString：" + jsonString);
        resp.getWriter().write(jsonString);
    }

    // 存储数据
    private void save(Message message) {
        // 把一条数据保存到数据库中
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 1. 建立连接
            connection = DBUtil.getConnection();
            // 2. 构造sql语句
            String sql = "insert into message values(?, ?, ?)";
            //    包装
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            // 3. 执行sql
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(connection, statement, null);
        }
    }

    private List<Message> load() {
        ArrayList<Message> messages = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messages.add(message);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return messages;
    }
}
